<?php

/**
 * Model MyAR
 *
 * @author luubk
 * @since Jan 14, 2013 - 2:40:14 PM
 */
class MyAR extends CActiveRecord
{

    public $activity_desc = "";
    public $log_activity  = FALSE;
    public $objectName    = '';
    public $tableName     = '';
    public $controlName   = '';

    function afterSave()
    {
        parent::afterSave();

        $type = $this->isNewRecord ? 'create' : 'update';
        $this->logActivity($type);
    }

    function afterDelete()
    {
        parent::afterDelete();
        $this->logActivity('delete');
    }

    protected function logActivity($type = 'create')
    {
        // Nếu không ghi Hoạt động thì bỏ qua
        if (!$this->log_activity)
            return TRUE;

        /**
         * Sau khi lưu bản ghi vào csdl, lưu hành động này vào bảng Activity
         */
        $act              = new Activity();
        $act->object_id   = is_array($this->primaryKey) ? current($this->primaryKey) : $this->primaryKey;
        $act->object_type = strtolower($this->tableName);
        $act->object_name = strtolower($this->objectName);
        $act->type        = $type;
        $act->created_at  = time();
        $act->description = $this->activity_desc;
        $act->ip          = (Yii::app()->request->userHostAddress) ? Yii::app()->request->userHostAddress : NULL;
        $act->url         = (isset(Yii::app()->request->url)) ? Yii::app()->request->url : NULL;
        if (isset(Yii::app()->controller->user))
            if (Yii::app()->controller->user != NULL)
            {
                $act->actor_id   = Yii::app()->user->id;
                $act->actor_type = Yii::app()->controller->user->getTableName();
            }
        $act->save();
    }

    protected function _getUrl($action, $pk = TRUE)
    {
        $params = array();

        if ($pk == TRUE)
        {
            $params['pk'] = $this->primaryKey;
        }

        if (isset($_GET['page']))
        {
            $params['page'] = $_GET['page'];
        }

        return Yii::app()->createUrl("$this->controlName/$action", $params);
    }

    public function getListUrl()
    {
        return $this->_getUrl('index', FALSE);
    }

    public function getCreateUrl()
    {
        return $this->_getUrl('create', FALSE);
    }

    public function getEditUrl()
    {
        return $this->_getUrl('edit');
    }

    public function getDeleteUrl()
    {
        return $this->_getUrl('delete');
    }

}

/** 
 * End file MyAR
 */
